<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>add user</title>
</head>
<body>

<?php
include '../dbconnect.php';

// 生成唯一的 SERVICE_ID
function generateServiceId($conn) {
    // 获取当前最大的 S_ID
    $sql = "SELECT U_ID FROM user ORDER BY U_ID DESC LIMIT 1";
    $result = $conn->query($sql);
    $row = $result->fetch_assoc();
    $max_id = $row['U_ID'];

    if ($max_id === null) {
        $next_id = 1;
    } else {
        $last_number = intval(substr($max_id, 4)); // 假设前缀是 "S_00"
        if ($last_number === 0) {
            $next_id = 1; 
        } else {
            $next_id = $last_number + 1;
        }
    }
    return "S_" . str_pad($next_id, 3, '0', STR_PAD_LEFT);
}

// 获取内容
$username = isset($_POST['username']) ? $_POST['username'] : '';
$password = isset($_POST['password']) ? $_POST['password'] : '';
$email = isset($_POST['email']) ? $_POST['email'] : '';

if (empty($username) || empty($password) || empty($email)) {
    echo "所有字段都是必填的！";
    exit;
}

// 检查用户名是否已存在
$check_sql = "SELECT * FROM user WHERE U_Username = ?";
$stmt = $conn->prepare($check_sql);
$stmt->bind_param("s", $username);
$stmt->execute();
$stmt->store_result();

if ($stmt->num_rows > 0) {
   echo "account already register，请<a href='../user/login.php'>login</a>！";
   echo "<script>
           setTimeout(function() {
             window.location.href = '../user/login.php';
           }, 2000);
         </script>";
    $stmt->close();
    $conn->close();
    exit;
}

$employeeId = generateServiceId($conn);

// 使用预处理语句写入数据库
$sql = "INSERT INTO user (U_ID, U_Username, U_Password, U_Email) VALUES (?, ?, ?, ?)";
$stmt = $conn->prepare($sql);
$stmt->bind_param("ssss", $employeeId, $username, $password, $email);

if ($stmt->execute()) {
    echo "注册成功，请<a href='../user/login.php'>登录</a>！";
    echo "<script>
            setTimeout(function() {
              window.location.href = '../user/login.php';
            }, 2000);
          </script>";
} else {
    echo "添加失败：" . $stmt->error;
}

$stmt->close();
$conn->close();
?>